package com.cw.starter.common.util;

import java.io.IOException;
import java.io.InputStream;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import cn.hutool.core.io.IoUtil;

public class SSHUtils {

    private static final String ENCODING = "UTF-8";

    public static Session getJSchSession(DestHost destHost) throws JSchException {
        JSch jsch = new JSch();

        Session session = jsch.getSession(destHost.getUsername(), destHost.getHost(), destHost.getPort());
        session.setPassword(destHost.getPassword());
        session.setConfig("StrictHostKeyChecking", "no");
        //第一次访问服务器不用输入yes
        session.setTimeout(destHost.getTimeout());
        session.connect();

        return session;
    }

    public static String execCommandByJSch(Session session, String command, String resultEncoding)
    throws IOException, JSchException {

        //1.默认方式，执行单句命令
        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand(command);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        String result = IoUtil.read(in, resultEncoding);
        channelExec.disconnect();
        session.disconnect();
        return result;

    }

    public static void main(String[] args) throws JSchException, IOException {
        DestHost destHost = new DestHost("47.104.152.97", "root", "Chenwei123@");
        //SSHUtils.execCommandByJSch(getJSchSession(destHost), "unzip -o /opt/project/jeeyt/logs/app.log.zip -d /", ENCODING);
        SSHUtils.execCommandByJSch(getJSchSession(destHost), "unzip -zvxf /opt/project/jeeyt/logs/app.log.zip", ENCODING);
    }
}